package models

import (
	"log"
	//"log"
	"net/http"
)

func init() {
	//初始化模块
}

func (this *Sut_user) Login(user_name string, user_password string) error {
	//验证用户成功后写入COOKIE
	var (
		sqlstr string
		err    error
	)
	sqlstr = `SELECT userId, userName FROM rbac_users
			WHERE deleted = 0 AND status = 1 AND userName=? AND password=password(?)`
	//log.Println("public.go Login查询:", sqlstr)
	err = db.QueryRow(sqlstr, user_name, user_password).Scan(&this.User_id, &this.User_name)
	if err != nil {
		log.Println("public.go Login 用户登录时，验证用户结果失败! 根据用户名和密码没有查到用户信息！！！用户名：", user_name, "，密码：", user_password, err)
		return err
	}
	//log.Println("login_model.go Login函数，写入cookie，User_name:", user.User_name, "，User_id:", user.User_id, "，User_role_id:", user.User_role_id)
	//http.SetCookie(w, &http.Cookie{Name: "User_name", Value: url.QueryEscape(this.User_name), Path: "/", MaxAge: Cookie_time})
	//http.SetCookie(w, &http.Cookie{Name: "User_id", Value: url.QueryEscape(string(this.User_id)), Path: "/", MaxAge: Cookie_time})
	//http.SetCookie(w, &http.Cookie{Name: "User_role_id", Value: url.QueryEscape(string(this.User_role_id)), Path: "/", MaxAge: Cookie_time})
	//****将url.QueryEscape("熊义")写入cookie后，要用的时候必须用url.QueryUnescape()还原
	return err
}

func (this *Sut_user) Logout(w http.ResponseWriter) {
	//删除COOKIE
	var ()
	//清除用户变量
	this.User_id = -1
	this.User_name = ""
	this.User_role_id = -1
	http.SetCookie(w, &http.Cookie{Name: "User_name", Path: "/", MaxAge: -1})
	http.SetCookie(w, &http.Cookie{Name: "User_id", Path: "/", MaxAge: -1})
	http.SetCookie(w, &http.Cookie{Name: "User_role_id", Path: "/", MaxAge: -1})
}

func (this *Sut_user) Is_login(w *http.Request) (ret int) {
	//本函数废除，使用beego.control.session来判断用户是否登录
	//验证COOKIE（User_name)是否存在以判断用户是否登陆
	var (
	//cookie *http.Cookie
	)
	/*不能够用cookie判断用户是否登录，因为cookie超时后就自动退出登录了
	_, err = w.Cookie("User_name")
	if err != nil {
		return -1, err
	}
	*/
	//name, err := url.QueryUnescape(cookie.Value)
	//log.Println("public.go Is_login COOKIE中User_name的值是：", cookie.Value, "url.QueryUnEscape转码还原后的值：", name)
	return this.User_id //用全局变量判断用户是否登录
}
